package tk.heimashuma.store.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.heimashuma.store.entity.Users;
import tk.heimashuma.store.repository.UserRepository;
import tk.heimashuma.store.service.UserService;
import tk.heimashuma.store.utils.SendMail;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public void registerUser(Users user) {
        userRepository.save(user);
    }

    @Override
    public Users login(Users user) {
        Users reUser = userRepository.findByUsernameAndPassword(user.getUsername(),user.getPassword());
        return reUser;
    }

    /**
     *  发送手机验证码
     * @param code
     * @return Boolean
     */
    @Override
    public Boolean sendIphoneCode(String code) {
        return true;
    }

    /**
     * 检查用户名是否已经存在
     * @param value
     * @return
     */
    @Override
    public Boolean checkUsername(String value) {
        String reUsername = userRepository.findUsernameByUsername(value);
        if(reUsername != null){
            return true;
        }
        return false;
    }

    @Override
    public Boolean checkEmail(String value) {
        String reEmail = userRepository.findEmailByEmail(value);
        if(reEmail != null){
            return true;
        }
        return false;
    }

    @Override
    public Boolean checkIphone(String value) {
        String reIphone = userRepository.findIphoneByIphone(value);
        if(reIphone != null){
            return true;
        }
        return false;
    }

    @Override
    public void sendMailCode(String emailCode, Users user) {
        StringBuffer msg = new StringBuffer("尊敬的用户你好:你正在注册黑马数码请单机下面的链接激活账号");
        // TODO 验证邮箱URL
        msg.append("http://localhost:8888/users/checkMail/");
        msg.append(emailCode);
        new Thread(new SendMail(user.getEmail(),msg.toString(),"黑马数码邮箱激活")).start();
    }

    @Override
    public boolean checkMailCode(String code) {
        Users user = userRepository.findByEmailCode(code);
        if(Optional.ofNullable(user).isPresent()){
            user.setEmailCode("0");
            userRepository.save(user);
            return true;
        }
        return false;
    }
}
